package framework.jackson.xml;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import org.junit.Assert;

import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;

/**
 *
 */
public class TestJacksonXmlList {

    public static void main(String[] args) throws Exception {
        XmlMapper xmlMapper = new XmlMapper();

        Sub1 sub1 = new Sub1();
        sub1.setId(1);
        sub1.setName("ljy");
        sub1.setAliases(Arrays.asList("肥鸡", "海牛"));
        String jsonStr1 = xmlMapper.writeValueAsString(sub1);
        System.out.println("sub1 -> xml: " + jsonStr1);
        String xmlString = "<sub111><id>1</id><name>ljy</name><alias>肥鸡</alias><alias>海牛</alias></sub111>";
        Assert.assertEquals("相同", xmlString, jsonStr1);

        System.out.println("\n反序列化成对象时，默认不丢弃类型标志符，需使用 `@JsonTypeInfo(visible = true)` 开启");
        System.out.println("xml -> sub1: " + xmlMapper.readValue(jsonStr1, Sub1.class).toString());
    }

    @JacksonXmlRootElement(localName = "sub111")
    private static class Sub1 {
        @JacksonXmlProperty(localName = "id")
        private int id;
        private String name;

        @JacksonXmlProperty(localName = "alias")
        @JacksonXmlElementWrapper(useWrapping = false)
        private List<String> aliases;

        public Sub1() {}

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public List<String> getAliases() {
            return aliases;
        }

        public void setAliases(List<String> aliases) {
            this.aliases = aliases;
        }

        @Override
        public String toString() {
            return new StringJoiner(", ", Sub1.class.getSimpleName() + "[", "]")
                    .add("id=" + id)
                    .add("name='" + name + "'")
                    .add("aliases=" + aliases)
                    .toString();
        }
    }

}
